<template>
    <div class="main">
        <div class="filter-container" v-if="rightsButtons['add']">
            <el-button type="success" icon="el-icon-plus" class="filter-item" @click="showAdd">新建活动</el-button>
        </div>
        <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border highlight-current-row>
            <el-table-column align="center" label="活动名称" prop="activityName"></el-table-column>
            <el-table-column align="center" label="活动时间">
                <template slot-scope="scope">
                    <span v-text="formatDate(scope.row.startTime, 'YYYY-MM-DD HH:mm:ss')"></span>
                    <span>至</span>
                    <span v-text="formatDate(scope.row.endTime, 'YYYY-MM-DD HH:mm:ss')"></span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="是否启用" width="150">
                <template slot-scope="scope">
                    <el-switch
                            v-model="scope.row.status"
                            @change="updateStatus(scope.row)"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            active-text="是"
                            inactive-text="否"
                            :active-value="1"
                            :inactive-value="2"
                            :disabled="!rightsButtons['operate']">
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column align="center" label="活动会员">
                <template slot-scope="scope">
                   <span v-if="scope.row.type===1">大区、董事</span>
                    <span v-if="scope.row.type===2">董事</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作" v-if="rightsButtons['edit'] || rightsButtons['goodsList']">
                <template slot-scope="scope">
                    <el-button v-if="rightsButtons['edit']" type="primary" size="mini" @click="showEdit(scope.row)">编辑</el-button>
                    <router-link v-if="rightsButtons['goodsList']" :to="{name: 'activityMemberGoodsList', params: {id: scope.row.id}}">
                        <el-button type="primary" plain size="mini">商品管理</el-button>
                    </router-link>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-container" v-if="listTotal > 0">
            <el-pagination @current-change="handleCurrentChange" :current-page.sync="listQuery.pageIndex" :page-size="listQuery.pageSize" :total="listTotal" layout="total, prev, pager, next, jumper"></el-pagination>
        </div>
        <el-dialog :title="editItem.id ? '编辑会员专享' : '新建会员专享'" :visible.sync="showEditPop">
            <el-form :model="editItem" :rules="editRule" size="medium" ref="editItem" label-width="120px">
                <el-form-item label="活动名称:" prop="activityName">
                    <el-input
                        v-model="editItem.activityName"
                        placeholder="请输入活动名称"
                        maxlength="20"
                    >
                    </el-input>
                </el-form-item>
                <el-form-item label="活动说明:" prop="activityDeclare">
                    <el-input
                        v-model="editItem.activityDeclare"
                        placeholder="请输入活动说明"
                        maxlength="50"
                    >
                    </el-input>
                </el-form-item>
                <el-form-item label="活动时间:" prop="timeRange">
                    <el-date-picker
                        v-model="editItem.timeRange"
                        type="datetimerange"
                        value-format="timestamp"
                        range-separator="~"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="活动会员:" prop="type">
                    <el-radio v-model="editItem.type" :disabled="!!editItem.id" :label="1">大区、董事</el-radio>
                    <el-radio v-model="editItem.type" :disabled="!!editItem.id" :label="2">董事</el-radio>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="save" :disabled="btnDisabled">保存</el-button>
                <el-button @click="showEditPop = false">取消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
  import { goodsCheck } from '@/api/activity/fullReduce'
    export default {
        name: 'activityMember',
        data(){
            return {
                listLoading: false,
                listQuery: {
                    pageIndex: 1,
                    pageSize: 10,
                    isPage: 1
                },
                list: [],
                listTotal: 0,
                showEditPop: false,
                btnDisabled: false,
                editItem: {
                    timeRange: [],
                    activityName: '',
                    activityDeclare: '',
                    type: 1
                },
                editRule: {
                     activityName: [
                        {required: true, message: '请输入活动名称', trigger: 'change'}
                    ],
                    activityDeclare: [
                        {required: true, message: '请输入活动描述', trigger: 'change'}
                    ],
                    timeRange: [
                        {required: true, message: '请选择活动时间', trigger: 'change'}
                    ],
                    type: [
                        {required: true, message: '请选择活动会员', trigger: 'change'}
                    ]
                }
            }
        },
        created(){
            this.getList();
        },
        methods: {
            getList(){
                this.listLoading = true;
                this.request({
                    url: '/vip-day/web-manage/page/get',
                    method: 'get',
                    params: this.listQuery
                }).then((res) => {
                    this.list = res.data.records
                    this.listTotal = Number(res.data.total)
                    this.listLoading = false
                }).catch(err => {
                    console.log(err)
                    this.list = []
                    this.listTotal = 0
                    this.listLoading = false
                });
            },
            updateStatus(item){
              // 启用的使用要判断下活动互斥的商品
              if (item.status === 1) {
                this.request({
                  url: '/vip-day/web-manage/goods-page/get',
                  method: 'get',
                  params:{ vipdayId: item.id }
                }).then( async ({data}) => {
                  // console.log(data)
                  if(data.length>0){
                    let flag =false
                    for(let i=0;i<data.length;i++){
                      const param = {
                        id: data[i].goodsId,
                        checkList: [1, 2, 3, 4] // 互斥类型
                      }
                      const res = await goodsCheck(param)
                      if (res.code*1 !== 200) {
                        flag = true
                        item.status = 2
                        break
                      }
                      if (i === data.length - 1 && !flag) {
                        this.updateStatusNext(item)
                      }
                    }
                  } else {
                    this.updateStatusNext(item)
                  }
                }).catch(err => {
                  console.log(err)
                });
              } else {
                this.updateStatusNext(item)
              }
            },
            // 启动下一步
            updateStatusNext(item) {
              this.request({
                  url: '/vip-day/web-manage/status/update',
                  method: 'post',
                  data: item
              }).then(() => {
                  this.$message.success(item.status === 1 ? '启用成功' : '禁用成功');
              }).catch(err => {
                  this.$message.error(err)
              });
            },
            showAdd(){
                this.editItem = {
                    timeRange: [],
                    activityName: '',
                    activityDeclare: '',
                    type: 1
                };
                this.showEditPop = true;
                this.btnDisabled = false;
            },
            showEdit(item){
                this.editItem = {
                    ...item,
                    timeRange: [item.startTime, item.endTime]
                };
                this.showEditPop = true;
                this.btnDisabled = false;
            },
            save(){
                this.$refs.editItem.validate(valid => {
                    if (!valid) {
                        return false;
                    }
                    let url = this.editItem.id ? '/vip-day/web-manage/update' : '/vip-day/web-manage/create';
                    let timeRange = this.editItem.timeRange;
                    if (timeRange && timeRange.length > 0) {
                        this.editItem.startTime = timeRange[0]
                        this.editItem.endTime = timeRange[1]
                    }
                    this.btnDisabled = true;
                    this.request({
                        url,
                        method: 'post',
                        data: this.editItem
                    }).then((res) => {
                      this.btnDisabled = false;
                      if (res.code === 200) {
                        this.editItem = {};
                        this.showEditPop = false;
                        this.$message.success('保存成功');
                        this.getList();
                      }
                    }).catch(err => {
                        this.btnDisabled = false;
                    });
                });
            },
            handleCurrentChange(val){
                this.listQuery.pageIndex = val;
                this.getList();
            },
            handleSizeChange(val){
                this.listQuery.pageSize = val;
                this.getList();
            }
        }
    }
</script>
